package com.tuanzi.loan.business.service.extratemplate.impl;

import com.tuanzi.loan.business.entity.extratemplate.ExtraTemplate;
import com.tuanzi.loan.business.entity.extratemplate.ExtraTemplateSpecial;
import com.tuanzi.loan.business.repository.extratemplate.ExtraTemplateRepository;
import com.tuanzi.loan.business.repository.extratemplate.ExtraTemplateSpecialRepository;
import com.tuanzi.loan.business.service.extratemplate.ExtraTemplateService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.core.repository.JPAAuditRepository;
import com.tuanzi.loan.core.service.BaseAuditServiceImpl;
import com.tuanzi.loan.core.vo.PageSearcher;
import com.tuanzi.loan.vo.request.extratemplate.ExtraTemplateRequest;
import com.tuanzi.loan.vo.response.extratemplate.ExtraTemplateResponse;
import com.tuanzi.server.loan_base.constant.LoanRedisKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.retry.RetryException;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author caiwanlin
 * @create 2018-10-16 14:36
 */
@Debug
@Service
@Transactional
@Retryable(value = {RetryException.class})
public class ExtraTemplateServiceImpl extends BaseAuditServiceImpl<ExtraTemplate,Long> implements ExtraTemplateService {
    @Autowired
    private ExtraTemplateRepository extraTemplateRepository;

    @Autowired
    private ExtraTemplateSpecialRepository extraTemplateSpecialRepository;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    protected JPAAuditRepository<ExtraTemplate, Long> getRepository() {
        return extraTemplateRepository;
    }

    @Override
    public Page<ExtraTemplateResponse> list(PageSearcher<ExtraTemplateRequest> pageSearcher) {
        return extraTemplateRepository.list(pageSearcher.getSearchCondition(),pageSearcher.getPageable());
    }

    @Override
    public void onSave(ExtraTemplate extraTemplate, List<ExtraTemplateSpecial> specialList) throws Exception {
        ExtraTemplate save = extraTemplateRepository.save(extraTemplate);
        if (specialList == null || specialList.isEmpty()) return;
        specialList.forEach(special ->{
            special.setTemplateId(save.getTemplateId());
        });
        extraTemplateSpecialRepository.save(specialList);
    }

    @Override
    public int countAllByTemplateId(Integer templateId) {
        return extraTemplateRepository.countAllByTemplateId(templateId);
    }

    @Override
    public void deleteExtraTemplateCache(Integer templateId) {
        stringRedisTemplate.delete(String.format(LoanRedisKey.LOAN_EXTRA_TEMPLATE,templateId));
    }
}
